var Request = (function() {
	var urlTemplate = "http://a.wykop.pl/{0}/{1}/appkey,{2},{3}";
	var params;
	
	var send = function(p) {
		params = p;
		var encodedURL = encodeURL(params.url);
		var callback = function(data){
			if(data.error && data.error.code){
				params.error(data);
			}else{
				var json = JSON.parse(data.substring(12, data.length - 2));
				
				if(json.error && json.error.code){
					params.error(json);
				}else{
					console.log("Answer:");
					console.log(json);
					params.success(json);
				}
			}
		};
		
		console.log("Request.URL = "+encodedURL);
		
		$.ajax({
			url: encodedURL,
			type: (params.post ? "POST" : "GET"),
			headers: {"apisign": sign(encodedURL, params.post)},
			async: !params.sync,
			data: params.post,
			success: callback,
			error: callback
		});
	};
	
	function encodeURL(url) {
		return urlTemplate.format(url.type, url.method, Application.APP_KEY, 
				(!url.param || url.param === "" ? "" : url.param+",") + Application.RESPONSE_FORMAT);
	}
	
	function sign(url, _post) {
		var post = "";
		
		if(_post) {
			post = $.param(_post);
			var postCouples = post.split("&");
			var values = [];
			
			postCouples.sort();
			
			$.each(postCouples, function(index, couple){
				values.push(couple.split("=")[1]);
			});
			
			post = values.join().split("+").join(" ");
		}
		
		return md5(Application.PRIVATE_API_KEY + url + post);
	}
	
	return {
		send: send
	};
})();